/*
 *    This file is part of CeluMap.
 *
 *    CeluMap is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    CeluMap is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Copyright 2006, 2007, 2008 Gonzalo Merayo
 *    gonzalo (at) celumap.com.ar
 *    www.celumap.com.ar
 *
 */

package main;


import geometry.Matrix;
import geometry.MovingTransform;
import geometry.Rectangle;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;

import mapDrawer.DefaultMapDrawer;
import mapDrawer.MapDrawer;
import screen.MapScreenBuffer;

public class MapCanvas extends Canvas implements Runnable {

	private static MapDrawer mapd = null;
	private static boolean wait = false;
	private static boolean invalidate;
	private static Thread thread;
	private static MovingTransform transform = null;
	private static boolean secondPassRequired = false;
	private static MapScreenBuffer b;
	private static int keys;
	private static Rectangle allArea;
	private FireListener l;
	private static final long animatorDelay=30;
	
	public MapCanvas(DefaultMapDrawer m, MovingTransform t) {
		super();
		setFullScreenMode(true);	
		mapd = m;
		transform = t;
		transform.setScreenCentre(getWidth()/2, getHeight()/2);
		b = new MapScreenBuffer(getWidth(), getHeight(), transform, mapd);
		allArea = new Rectangle(0,0,b.getWidth(),b.getHeight());
	}

	protected void keyPressed(int keyCode) {
	    int gameAction = getGameAction(keyCode);
	    switch(gameAction) {
	      case UP:     keys |= GameCanvas.UP_PRESSED; break;
	      case DOWN:   keys |= GameCanvas.DOWN_PRESSED; break;
	      case LEFT:   keys |= GameCanvas.LEFT_PRESSED;  break;
	      case RIGHT:  keys |= GameCanvas.RIGHT_PRESSED;  break;
	      case GAME_A: keys |= GameCanvas.GAME_A_PRESSED;  break;
	      case GAME_B: keys |= GameCanvas.GAME_B_PRESSED;  break;
	      case GAME_C: keys |= GameCanvas.GAME_C_PRESSED; break;
	      case GAME_D: keys |= GameCanvas.GAME_D_PRESSED; break;
	      case FIRE: fire(); break;
	    }
	}
	
	private void fire() {
		l.fire();
	}

	protected void keyReleased(int keyCode) {
		int gameAction = getGameAction(keyCode);
	    switch(gameAction) {
	      case UP:     keys &= ~GameCanvas.UP_PRESSED; break;
	      case DOWN:   keys &= ~GameCanvas.DOWN_PRESSED;           break;
	      case LEFT:   keys &= ~GameCanvas.LEFT_PRESSED;           break;
	      case RIGHT:  keys &= ~GameCanvas.RIGHT_PRESSED;          break;
	      case GAME_A: keys &= ~GameCanvas.GAME_A_PRESSED;         break;
	      case GAME_B: keys &= ~GameCanvas.GAME_B_PRESSED;         break;
	      case GAME_C: keys &= ~GameCanvas.GAME_C_PRESSED;         break;
	      case GAME_D: keys &= ~GameCanvas.GAME_D_PRESSED;         break;
	    }
	}

	
	private boolean processTransform(MapScreenBuffer b){
		
		if((keys & GameCanvas.UP_PRESSED)!=0)
			b.shiftUp();
		if((keys & GameCanvas.DOWN_PRESSED)!=0)
			b.shiftDown();
		if((keys & GameCanvas.LEFT_PRESSED)!=0)
			b.shiftLeft();
		if((keys & GameCanvas.RIGHT_PRESSED)!=0)
			b.shiftRight();
		if((keys & GameCanvas.GAME_A_PRESSED)!=0)
			b.zoom((5<<Matrix.nshift)>>2);
		if((keys & GameCanvas.GAME_B_PRESSED)!=0)
			b.zoom((3<<Matrix.nshift)>>2);
		/*if(secondPassArea != null && (secondPassArea.xi>=secondPassArea.xf || secondPassArea.yi>=secondPassArea.yf))
			secondPassArea = null;*/ 
		//if((keys & GameCanvas.GAME_C_PRESSED)!=0)
		//if((keys & GameCanvas.GAME_D_PRESSED)!=0)
		return keys != 0;
	}
	
	protected void paint(Graphics g) {
		pleaseWait();
		if(invalidate){
			b.drawFirstPass(allArea);
			b.drawSecondPass();
			b.paint(g);
			b.drawVolatilePass(g, allArea);
			invalidate = false;
		}else{
			if(processTransform(b)){
				b.paint(g);
				secondPassRequired = true;
			}else{
				if(secondPassRequired){
					//if(dirtyScreen!=null)
					//	b.drawFirstPass(dirtyScreen);
					b.drawSecondPass();
					b.paint(g);
					b.drawVolatilePass(g, allArea);
					secondPassRequired = false;
				}else{
					b.paint(g);
					b.drawVolatilePass(g, allArea);
				}
			}
		}
		pleaseResume();
	}

	public void invalidate() {
		invalidate = true;
	}

	public void pleaseWait(){
        wait = true;
	}
	
	public void pleaseResume(){
		wait = false;
	}

	public void start() {
		thread = new Thread(this);
		thread.start();
		invalidate = true;
	}

	public void run() {
		long milis =0;
		try{
			while(true){
				if((!wait && (keys!=0 || secondPassRequired || invalidate ))||((System.currentTimeMillis()-milis)>animatorDelay)){
					repaint();
					milis = System.currentTimeMillis();
					pleaseWait();
				}
				
				Thread.sleep(1);
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	public void setFireListener(FireListener listener) {
		l = listener;
	}

}
